/*
 * @Author: byron
 * @Date: 2021-11-05 16:12:03
 * @LastEditTime: 2022-02-11 14:18:12
 */
import {
    getTags
} from '@/api/module/tags.js'
import {
    getArticles
} from '@/api/module/article.js'
import {
    message
} from 'ant-design-vue'

const state = {
    pageView: localStorage.getItem('USER_POWERS') != null ?
        localStorage.getItem('USER_POWERS') : [],
    articleNum: localStorage.getItem('ARTICLE_NUM') != null ?
        localStorage.getItem('ARTICLE_NUM') : '',
    tagNum: localStorage.getItem('TAG_NUM') != null ?
        localStorage.getItem('TAG_NUM') : null,
    userNum: localStorage.getItem('USER_NUM') != null ?
        localStorage.getItem('USER_NUM') : [],
}

// 同步方法
const mutations = {
    SET_ARTICLE_NUM(state, articleNum) {
        if (articleNum) {
            state.articleNum = articleNum
            localStorage.setItem('ARTICLE_NUM', articleNum)
        } else {
            state.articleNum = ''
            localStorage.removeItem('ARTICLE_NUM')
        }
    },
    SET_TAG_NUM(state, tagNum) {
        if (tagNum) {
            state.tagNum = tagNum
            localStorage.setItem('TAG_NUM', tagNum)
        } else {
            state.tagNum = ''
            localStorage.removeItem('TAG_NUM')
        }
    },
    SET_USER_NUM(state, userNum) {
        if (userNum) {
            state.userNum = userNum
            localStorage.setItem('USER_NUM', userNum)
        } else {
            state.userNum = ''
            localStorage.removeItem('USER_NUM')
        }
    },
}

// 异步方法
const actions = {
    async getTagNum({
        commit
    }) {
        try {
            const response = await getTags()
            const {
                code,
                data
            } = response
            if (code === 200) {
                const {
                    total
                } = data
                commit('SET_TAG_NUM', total)
                return Promise.resolve()
            } else {
                return Promise.reject(message)
            }
        } catch (e) {
            console.log(e)
        }
    },
    async getArticleNum({
        commit
    }) {
        try {
            const response = await getArticles()
            const {
                code,
                data
            } = response
            if (code === 200) {
                const {
                    total
                } = data
                commit('SET_ARTICLE_NUM', total)
                return Promise.resolve()
            } else {
                return Promise.reject(message)
            }
        } catch (e) {
            console.log(e)
        }
    },
}

export default {
    namespaced: true,
    mutations,
    actions,
    state,
}